﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace PhoenixCrabV6.Engine.IO
{
    public class XmlManager<T> : IXmlManager<T>
    {
        public Type Type { get; set; }

        public XmlManager()
        {
            Type = typeof (T);
        }
        
        /// <summary>
        /// Deseralizes an XML file and enters the info into a new object of type T
        /// </summary>
        /// <param name="path">The path of file to deserialize</param>
        /// <returns>Object of type T built from Deserialized XML</returns>
        public T Load(string path)
        {
            using (TextReader reader = new StreamReader(path))
            {
                var xml = new XmlSerializer(Type);
                return (T) xml.Deserialize(reader);
            }
        }

        /// <summary>
        /// Serializes object into XML File
        /// </summary>
        /// <param name="path">path to the XML file</param>
        /// <param name="obj">object to be serialized</param>
        public void Save(string path, T obj)
        {
            using (TextWriter writer = new StreamWriter(path))
            {
                var xml = new XmlSerializer(Type);
                xml.Serialize(writer, obj);
            }
        }
    }
}